package com.ycz.algorithm.utils.heap;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author yancz
 * @ClassName HeapUtil
 * @description: 堆常用操作工具类
 * @date 2025-01-08 10:39:10
 * @version: 1.0
 */
public class HeapUtil {

    public static void main(String[] args) {
        // 初始化小顶堆
        Queue<Integer> minHeap = new PriorityQueue<>();
        // 初始化大顶堆，修改lambda表达式，将元素a和b进行比较，返回b-a，即从大到小排序
        Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
        // 元素入大顶堆
        maxHeap.offer(1);
        maxHeap.offer(3);
        maxHeap.offer(2);
        maxHeap.offer(5);
        maxHeap.offer(4);
        for (int i : maxHeap) {
            System.out.print(i + "\t");
        }
        System.out.println();
        // 获取堆顶元素
        System.out.println("堆顶元素：" + maxHeap.peek());
        System.out.println("堆大小：" + maxHeap.size());
        // 堆顶元素出堆，出堆后，堆中元素会自动调整为大顶堆
        System.out.println("出堆元素：" + maxHeap.poll());
        System.out.println("堆顶元素：" + maxHeap.peek());
        System.out.println("堆大小：" + maxHeap.size());
        System.out.println("堆是否为空？" + maxHeap.isEmpty());
        for (int i : maxHeap) {
            System.out.print(i + "\t");
        }
        System.out.println();
        // 输入列表并建立小顶堆
        minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
        for (int i : minHeap) {
            System.out.print(i + "\t");
        }
    }

}
